<script setup lang="ts">
import type { CellValueChangedEvent } from 'ag-grid-community'

import { provide, reactive, ref, watch } from 'vue'

import { alert } from '@vben/common-ui'
import { useAccessStore } from '@vben/stores'

import { AgGridVue } from 'ag-grid-vue3'
import { Button, Card, message, Space, Upload } from 'ant-design-vue'
import dayjs from 'dayjs'

import { v2GoodsPurchaseAdd } from '#/api/goodsPurchaseDetail'
import { getUrl } from '#/utils'
import { indexData } from '#/views/backend/batchOrdering/state'
import rightColumnActionsRenderer from '#/views/backend/spuBom/components/agGridVueComponents/rightColumnActionsRenderer.vue'

import detailComponent from './detailComponent.vue'
import selectDate from './selectDate.vue'
import selectGoods from './selectGoods.vue'
import selectType from './selectType.vue'
import { stop } from './state'
import 'ag-grid-enterprise'

import 'ag-grid-community/styles/ag-grid.css'
import 'ag-grid-community/styles/ag-theme-quartz.css'

const materialGridRef = ref()

// 你自己的业务函数
function dataChange(newVal, oldVal) {
  const goods = newVal
  const t = goods.slice(0, -1)
  const list = t.map((item: any) => ({
    goodsName: `${item.goods_no}/${item.template.template_no}`,
    color: item.color?.name || '',
    goodsId: item.goods_id,
    id: item.goods_id,
    orderNum: 0,
    price: item.purchase_price || 0,
    purchaseDate: dayjs().format('YYYY-MM-DD'),
    deliveryDate: undefined,
    purchaseType: '',
    pavingArea: '',
    isExpanded: true,
    bomList: {
      materialData: [],
      processData: [],
    },
    orderWareList: [
      { wareName: '广州云仓', shopNum: 0, first: 0, second: 0, third: 0, fourth: 0, fifth: 0, sixth: 0, seventh: 0, eighth: 0, ninth: 0, tenth: 0, eleven: 0, twelve: 0, total: 0 },
      { wareName: '南昌云仓', shopNum: 0, first: 0, second: 0, third: 0, fourth: 0, fifth: 0, sixth: 0, seventh: 0, eighth: 0, ninth: 0, tenth: 0, eleven: 0, twelve: 0, total: 0 },
      { wareName: '长沙云仓', shopNum: 0, first: 0, second: 0, third: 0, fourth: 0, fifth: 0, sixth: 0, seventh: 0, eighth: 0, ninth: 0, tenth: 0, eleven: 0, twelve: 0, total: 0 },
      { wareName: '贵阳云仓', shopNum: 0, first: 0, second: 0, third: 0, fourth: 0, fifth: 0, sixth: 0, seventh: 0, eighth: 0, ninth: 0, tenth: 0, eleven: 0, twelve: 0, total: 0 },
      { wareName: '武汉云仓', shopNum: 0, first: 0, second: 0, third: 0, fourth: 0, fifth: 0, sixth: 0, seventh: 0, eighth: 0, ninth: 0, tenth: 0, eleven: 0, twelve: 0, total: 0 },
      { wareName: '西安云仓', shopNum: 0, first: 0, second: 0, third: 0, fourth: 0, fifth: 0, sixth: 0, seventh: 0, eighth: 0, ninth: 0, tenth: 0, eleven: 0, twelve: 0, total: 0 },
      { wareName: '合计', shopNum: 0, first: 0, second: 0, third: 0, fourth: 0, fifth: 0, sixth: 0, seventh: 0, eighth: 0, ninth: 0, tenth: 0, eleven: 0, twelve: 0, total: 0 },
    ],
  }))

  const mdata = JSON.parse(JSON.stringify(info.formData.goodsList))
  const newdata = [...mdata, ...list]
  info.formData.goodsList = newdata
}
watch(indexData, dataChange, { immediate: false })
const date = new Date()

const templateData = {
  goodsId: '',
  id: 0,
  goodsName: '',
  color: '',
  purchaseType: '',
  purchaseDate: dayjs(date).format('YYYY-MM-DD'),

  deliveryDate: undefined,
  orderNum: 0,
  price: 0,
  pavingArea: '',
  isExpanded: true, // 是否折叠
  bomList: {
    materialData: [],
    processData: [],
  },
  orderWareList: [
    {
      wareName: '广州云仓',
      shopNum: 0,
      first: 0,
      second: 0,
      third: 0,
      fourth: 0,
      fifth: 0,
      sixth: 0,
      seventh: 0,
      eighth: 0,
      ninth: 0,
      tenth: 0,
      eleven: 0,
      twelve: 0,
      total: 0,
    },
    {
      wareName: '南昌云仓',
      shopNum: 0,
      first: 0,
      second: 0,
      third: 0,
      fourth: 0,
      fifth: 0,
      sixth: 0,
      seventh: 0,
      eighth: 0,
      ninth: 0,
      tenth: 0,
      eleven: 0,
      twelve: 0,
      total: 0,
    },
    {
      wareName: '长沙云仓',
      shopNum: 0,
      first: 0,
      second: 0,
      third: 0,
      fourth: 0,
      fifth: 0,
      sixth: 0,
      seventh: 0,
      eighth: 0,
      ninth: 0,
      tenth: 0,
      eleven: 0,
      twelve: 0,
      total: 0,
    },
    {
      wareName: '贵阳云仓',
      shopNum: 0,
      first: 0,
      second: 0,
      third: 0,
      fourth: 0,
      fifth: 0,
      sixth: 0,
      seventh: 0,
      eighth: 0,
      ninth: 0,
      tenth: 0,
      eleven: 0,
      twelve: 0,
      total: 0,
    },
    {
      wareName: '武汉云仓',
      shopNum: 0,
      first: 0,
      second: 0,
      third: 0,
      fourth: 0,
      fifth: 0,
      sixth: 0,
      seventh: 0,
      eighth: 0,
      ninth: 0,
      tenth: 0,
      eleven: 0,
      twelve: 0,
      total: 0,
    },
    {
      wareName: '西安云仓',
      shopNum: 0,
      first: 0,
      second: 0,
      third: 0,
      fourth: 0,
      fifth: 0,
      sixth: 0,
      seventh: 0,
      eighth: 0,
      ninth: 0,
      tenth: 0,
      eleven: 0,
      twelve: 0,
      total: 0,
    },
    {
      wareName: '合计',
      shopNum: 0,
      first: 0,
      second: 0,
      third: 0,
      fourth: 0,
      fifth: 0,
      sixth: 0,
      seventh: 0,
      eighth: 0,
      ninth: 0,
      tenth: 0,
      eleven: 0,
      twelve: 0,
      total: 0,
    },
  ],
}
const info = reactive({
  formData: {
    goodsList: [],
  } as any,
})

// 使用响应式标志跟踪grid是否初始化完成
const gridInitialized = ref(false)

// 存储待处理的更新请求
const pendingUpdates = ref<Array<{ id: number | string; value: number }>>([])

// 当grid组件挂载完成后触发
const handleGridReady = () => {
  gridInitialized.value = true
  // 处理所有待处理的更新请求
  if (pendingUpdates.value.length > 0) {
    pendingUpdates.value.forEach((update) => {
      updateRowNode(update.id, update.value)
    })
    pendingUpdates.value = []
  }
}

// 更新行数据的核心函数
const updateRowNode = (id: number | string, value: number) => {
  try {
    if (materialGridRef?.value?.api) {
      const rowNode = materialGridRef.value.api.getRowNode(id)
      if (rowNode) {
        rowNode.setDataValue('orderNum', value)

        rowNode.setExpanded(true) // 展开这一行
        return
      }
    }
  } catch (error) {
    console.warn('更新行数据失败:', error)
  }
  return false
}

// 提供给子组件的更新函数
provide('sendToGrandPa', (data: any) => {
  // if (data.ts.total !== 0) {
  //   // 如果grid已初始化，则直接更新
  //   if (gridInitialized.value) {
  //     const success = updateRowNode(data.ts.id, data.ts.total)
  //     // 如果更新失败（可能grid被销毁），则添加到待处理队列
  //     if (!success) {
  //       pendingUpdates.value.push({ id: data.ts.id, value: data.ts.total })
  //       // 设置一个短暂的延时后重试
  //       setTimeout(() => {
  //         updateRowNode(data.ts.id, data.ts.total)
  //       }, 100)
  //     }
  //   } else {
  //     // 如果grid未初始化，则添加到待处理队列
  //     pendingUpdates.value.push({ id: data.ts.id, value: data.ts.total })
  //   }
  // }
  // const mdata = [...info.formData.goodsList]
  // const index = mdata.findIndex((item: any) => item.id === data.ts.id)
  // mdata[index].orderNum = data.ts.total
  // info.formData.goodsList = mdata
})
const getDownload = () => {
  const dom = document.createElement('a')
  const url = `${getUrl()}/static/template/商企下单导入模版.xlsx`
  dom.setAttribute('href', url)
  dom.setAttribute('download', '商企下单导入模版.xlsx')
  dom.click()
}

const Options: any = ref({
  masterDetail: true,
  detailCellRenderer: detailComponent,
  detailRowAutoHeight: true,
  // getRowId: (params) => params.data.id,
  // deltaRowDataMode: true, // 启用增量数据模式
  components: { rightColumnActionsRenderer, selectGoods, selectType, selectDate },
  columnDefs: [
    {
      headerName: '序号',
      field: 'id',
      editable: false,
      cellClass: 'borderCcc',
      filter: true,
      suppressMenu: true, // 仅此列不显示菜单按钮
      pinned: 'left',
      width: 50,
      cellStyle: {
        textAlign: 'center',
      },
      cellRenderer: 'agGroupCellRenderer',
      // 解决master/detail模式下序号不连续的问题
      // 直接使用数据数组中的索引来生成连续序号
      valueGetter: (params) => {
        // 检查是否有数据和参数有效
        if (params.data && info.formData.goodsList && info.formData.goodsList.length > 0) {
          // 查找当前数据在原始数据数组中的索引位置
          const index = info.formData.goodsList.indexOf(params.data)
          // 如果找到匹配项，返回索引+1作为序号
          // 如果未找到（可能是过滤或排序后），则回退到使用rowIndex
          return index === -1 ? params.node.rowIndex + 1 : index + 1
        }
        // 默认情况：使用rowIndex+1
        return params.node.rowIndex + 1
      },
    },
    {
      headerName: '货号',
      field: 'goodsName',
      editable: true,
      cellClass: 'borderCcc',
      suppressMenu: true, // 仅此列不显示菜单按钮
      cellEditor: 'selectGoods', // 使用自定义渲染组件
      width: 300,
      cellStyle: {
        textAlign: 'center',
      },
    },
    {
      headerName: '颜色',
      field: 'color',
      editable: false,
      cellClass: 'borderCcc',
      suppressMenu: true, // 仅此列不显示菜单按钮
      width: 120,
      // cellRenderer: 'selectDate', // 使用自定义渲染组件
      cellStyle: {
        textAlign: 'center',
      },
    },
    {
      headerName: '采购性质',
      field: 'purchaseName',
      editable: true,
      cellClass: 'borderCcc',
      suppressMenu: true, // 仅此列不显示菜单按钮
      width: 200,
      cellEditor: 'selectType', // 使用自定义渲染组件
      cellStyle: {
        textAlign: 'center',
      },
    },

    {
      headerName: '订单件数',
      field: 'orderNum',
      editable: true,
      cellClass: 'borderCcc',
      cellDataType: 'number',
      suppressMenu: true, // 仅此列不显示菜单按钮
      width: 200,
      cellStyle: {
        textAlign: 'center',
      },
    },

    {
      headerName: '本次铺货备注',
      field: 'pavingArea',
      editable: true,
      cellClass: 'borderCcc',
      // cellEditor: 'ElDateEditorComponent',
      // cellEditorPopup: true // 推荐弹出式编辑器
      suppressMenu: true, // 仅此列不显示菜单按钮
      width: 380,
      cellStyle: {
        textAlign: 'center',
      },
    },

    {
      headerName: '采购日期',
      field: 'purchaseDate',
      editable: false,
      cellClass: 'borderCcc',
      suppressMenu: true, // 仅此列不显示菜单按钮
      width: 280,
      // cellRenderer: 'selectDate', // 使用自定义渲染组件
      cellStyle: {
        textAlign: 'center',
      },
    },
    {
      headerName: '交货日期',
      field: 'deliveryDate',
      editable: true,
      cellDataType: 'date',
      cellClass: 'borderCcc',
      suppressMenu: true, // 仅此列不显示菜单按钮
      width: 280,
      // cellRenderer: 'selectDate', // 使用自定义渲染组件
      cellStyle: {
        textAlign: 'center',
      },
    },
    {
      headerName: '采购价',
      field: 'price',
      editable: true,
      cellDataType: 'number',
      cellClass: 'borderCcc',
      // cellEditor: 'ElDateEditorComponent',
      // cellEditorPopup: true // 推荐弹出式编辑器
      suppressMenu: true, // 仅此列不显示菜单按钮
      width: 265,
      cellStyle: {
        textAlign: 'center',
      },
    },
    {
      headerName: '操作',
      cellClass: 'borderCcc',
      editable: false,
      suppressMenu: true, // 仅此列不显示菜单按钮
      field: 'actions',
      // pinned: 'right', // 固定在右侧

      cellRenderer: 'rightColumnActionsRenderer', // 使用自定义渲染组件
      cellRendererParams: {
        context: {
          buttons: ['del'],
          deleteRow: (index) => {
            // 传递删除方法到渲染器
            const pData = [...info.formData.goodsList]

            pData.splice(index, 1)
            info.formData.goodsList = pData
          },
        },
      },
    },
  ],
  rowData: [],
  height: '600px', // 设置整个表格的高度为400px

  rowHeight: 30, // 设置全局行高为50px
  enableRangeSelection: true,
  enableFillHandle: true, // 开启拖动复制
  suppressClearOnFillReduction: false, // 可选：控制填充行为
  defaultColDef: {
    editable: true, // 必须设置为可编辑，否则无法复制
  },
  suppressClickEdit: false, // 禁用单击即编辑
  rowDragManaged: true, // 启用托管拖拽
  editType: 'cellEditor', // fullRow,cellEditor
  getContextMenuItems: (params: any) => {
    const result = [
      'export',
      {
        name: '向上插入一行',
        action: () => {
          const newRow = JSON.parse(JSON.stringify(templateData))
          newRow.id = info.formData.goodsList.length
          const selectedNode = params.node
          const mData = [...info.formData.goodsList]
          const startIndex = selectedNode ? Math.max(selectedNode.rowIndex, 0) : 0
          mData.splice(startIndex, 0, newRow)
          info.formData.goodsList = mData
        },
      },
      {
        name: '向下插入一行',
        action: () => {
          const newRow = JSON.parse(JSON.stringify(templateData))
          newRow.id = info.formData.goodsList.length
          const selectedNode = params.node
          const mData = [...info.formData.goodsList]
          const startIndex = selectedNode ? selectedNode.rowIndex + 1 : 0
          mData.splice(startIndex, 0, newRow)
          info.formData.goodsList = mData
        },
      },
      {
        name: '删除选中行',
        action: () => {
          const getCellRanges = params.api.getCellRanges()[0]
          const infoStartRow = getCellRanges.startRow.rowIndex
          const infoEndRow = getCellRanges.endRow.rowIndex
          const startRow = Math.max(infoEndRow, infoStartRow)
          const endRow = Math.min(infoEndRow, infoStartRow)
          const pData = [...info.formData.goodsList]
          for (let i = startRow; i >= endRow; i--) {
            pData.splice(i, 1)
          }
          info.formData.goodsList = pData
        },
      },
    ]
    return result
  },
  onRowDragEnd: (event: any) => {
    const newOrder: any = []
    event.api.forEachNode((node: any) => {
      newOrder.push(node.data)
    })
    info.formData.goodsList = newOrder // 更新响应式数组
  },
  onCellValueChanged: (params: CellValueChangedEvent) => {
    const rowIndex: any = params.rowIndex
    const field: any = params.colDef.field
    const newValue: any = params.newValue
    // 更新响应式数据
    const updated: any = [...info.formData.goodsList]
    updated[rowIndex] = {
      ...updated[rowIndex],
      [field]: newValue,
    }
    info.formData.goodsList = updated
  },
})
// 导入文件列表
const fileList = ref<any[]>([])
// 上传组件引用
const uploadRef = ref()
// 上传加载状态
const isUploading = ref(false)

// 处理上传开始事件
const handleUploadStart = () => {
  isUploading.value = true
}
// 处理导入成功回调，检查业务逻辑是否成功
const handleImportSuccess = (response: any) => {
  // 关闭加载状态
  isUploading.value = false
  // 如果业务逻辑失败(code=0)，手动触发错误处理
  if (response.code === 1) {
    message.success('导入成功', 5)
    alert({
      content: response.msg,
      icon: 'success',
    })
  } else {
    alert({
      content: response.msg,
      icon: 'error',
    })
  }
}

// 处理导入失败回调

const accessStore = useAccessStore()
const customHeaders = {
  batoken: accessStore.accessToken ?? '',
  'X-Requested-With': 'XMLHttpRequest',
}

function handadd() {
  const newRow = JSON.parse(JSON.stringify(templateData))
  newRow.id = info.formData.goodsList.length
  const mData = [...info.formData.goodsList]
  mData.push(newRow)
  info.formData.goodsList = mData
}

// 保存数据
async function saveData() {
  materialGridRef.value?.api?.stopEditing()
  stop.value = !stop.value
  const formData = JSON.parse(JSON.stringify(info.formData))
  formData.goodsList.forEach((g) => g.bomList.materialData?.forEach((row, idx) => (row.sort = idx + 1)))
  formData.goodsList.forEach((g) => g.bomList.processData?.forEach((row, idx) => (row.sort = idx + 1)))

  formData.goodsList.forEach((g) => {
    g.deliveryDate = dayjs(g.deliveryDate).format('YYYY-MM-DD')
    g.purchaseDate = dayjs(g.purchaseDate).format('YYYY-MM-DD')
    const index = g.orderWareList.findIndex((item: any) => item.wareName === '合计')
    if (g.orderWareList[index].total != 0) {
      g.orderNum = g.orderWareList[index].total
    }

    g.orderWareList.splice(index, 1)
  })

  // 验证每行的采购性质是否填写
  const invalidRows = formData.goodsList.filter((item, index) => {
    return item.purchaseType === ''
  })

  if (invalidRows.length > 0) {
    // 获取所有未填写采购性质的行号（从1开始）
    const invalidRowNumbers = formData.goodsList
      .map((item, index) => (!item.purchaseType || typeof item.purchaseType !== 'string' || item.purchaseType.trim() === '' ? index + 1 : null))
      .filter(Boolean)
      .join(', ')

    message.error(`请填写第 ${invalidRowNumbers} 行的采购性质`)
    return
  }

  v2GoodsPurchaseAdd({ formData }).then((res) => {
    if (res.data.code === 1) {
      info.formData.goodsList = []
      message.success(res.data.msg)
    } else if (res.data.code === 0) {
      message.error(res.data.msg)
    } else {
      message.error('系统错误')
    }
  })
}


</script>

<template>
  <Card style="margin: 8px; height: 98%">
    <Space class="mb-3">
      <Upload
        ref="uploadRef"
        :headers="customHeaders"
        :action="`${getUrl()}/admin/v2.GoodsPurchase/importData`"

        :on-success="handleImportSuccess"
        :on-start="handleUploadStart"
        :file-list="fileList"
        :multiple="false"
        accept=".xlsx,.xls"
        :show-upload-list="false"
      >
        <template #default>
          <Button type="primary" :loading="isUploading"> 导入数据 </Button>
        </template>
      </Upload>
      <Button type="primary" @click="getDownload">下载模板</Button>
      <Button type="primary" @click="handadd">添加行</Button>
    </Space>

    <AgGridVue ref="materialGridRef" :row-data="info.formData.goodsList" :grid-options="Options" @grid-ready="handleGridReady" class="ag-theme-quartz" style="flex-grow: 1; height: 800px; overflow-y: scroll" borderd />

    <!-- 右下方的保存按钮 -->
    <div style="text-align: right; margin-top: 10px">
      <Button type="primary" @click="saveData">保存</Button>
    </div>
  </Card>
</template>

<style lang="scss" scoped>
.highlight-row {
  color: #f0f9eb !important; // 高亮背景颜色
}
.text-red-500 {
  color: red; // 红色字体
}
.drag-separator:hover {
  background-color: #bbb;
  cursor: ew-resize; /* 左右拖拽指针 */
}

.custom-card {
  height: 100%;
  border-radius: 0 !important; /* 设置卡片的边角为直角 */
}

// 设置ag-grid-table单元格边框

:deep(.borderCcc) {
  // 表体单元格右边框
  border-right: 1px solid #ccc;
}
:deep(.ag-cell, .ag-full-width-row .ag-cell-wrapper.ag-row-group) {
  // 表体左右内边距
  padding: 0;
}

:deep(
//.ag-theme-balham .ag-header-cell-label,
//.ag-theme-alpine .ag-header-cell-label,
.ag-theme-quartz .ag-header-cell-label) {
  // 表头标题居中
  justify-content: center;
  display: flex;
  align-items: center;
}
:deep(.ag-header-cell, .ag-header-group-cell) {
  // 表头左右内边距
  padding: 0;
}
:deep(.ag-ltr .ag-header-viewport .ag-header-cell-resize::after) {
  // 表头右边框
  left: calc(50% - 0px);
}
:deep(.ag-header-cell-resize::after) {
  // 表头右边框
  width: 1px;
  height: 100%;
  top: 0;
}
</style>
